package com.example.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.core.Result;
import com.example.common.core.ResultGenerator;
import com.example.system.dao.AdminDao;
import com.example.system.dao.AdminRoleDao;
import com.example.system.dto.AdminParam;
import com.example.system.dto.AdminResult;
import com.example.system.model.Admin;
import com.example.system.model.AdminRole;
import com.example.system.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminDao adminDao;
    @Resource
    private AdminRoleDao adminRoleDao;

    @Value("${uploadPath}")
    private String uploadPath;

    @Override
    public Result add(AdminParam adminParam) {
        Admin adminByName= adminDao.selectByName(adminParam.getName());
        if(ObjectUtil.isNotNull(adminByName)){
            return ResultGenerator.genFailResult("名称已存在");
        }
        Admin adminByUserName = adminDao.selectByUserName(adminParam.getUsername());
        if(ObjectUtil.isNotNull(adminByUserName)){
            return ResultGenerator.genFailResult("账户已存在");
        }
        adminParam.setPassword(DigestUtils.md5DigestAsHex(adminParam.getPassword().getBytes()));
        Admin admin = BeanUtil.copyProperties(adminParam, Admin.class);
        adminDao.insertSelective(admin);
        List<Integer> roleIds = adminParam.getRoleIds();
        if(CollUtil.isNotEmpty(roleIds)){
            List<AdminRole> adminRoles = roleIds.stream().map(roleId -> new AdminRole(null, admin.getId(), roleId)).collect(Collectors.toList());
            adminRoleDao.insertList(adminRoles);
        }
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result delete(Integer id) {
       return deleteBatch(Arrays.asList(id));
    }

    @Override
    public Result deleteBatch(List<Integer> ids) {
        adminDao.deleteBatchByPrimaryKeys(ids);
        adminRoleDao.deleteBatchByAdminIds(ids);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result update(AdminParam adminParam) {
        Admin admin = adminDao.selectByPrimaryKey(adminParam.getId());
        if(ObjectUtil.isNull(admin)){
            return ResultGenerator.genFailResult("管理员不存在");
        }
        Admin adminByName= adminDao.selectByName(adminParam.getName());
        if(ObjectUtil.isNotNull(adminByName)&&adminByName.getId()!=admin.getId()){
            return ResultGenerator.genFailResult("名称已存在");
        }
        Admin adminByUserName = adminDao.selectByUserName(adminParam.getUsername());
        if(ObjectUtil.isNotNull(adminByUserName)&&adminByUserName.getId()!=admin.getId()){
            return ResultGenerator.genFailResult("账户已存在");
        }
        adminParam.setPassword(DigestUtils.md5DigestAsHex(adminParam.getPassword().getBytes()));
        adminDao.updateByPrimaryKeySelective(BeanUtil.copyProperties(adminParam, Admin.class));

        List<Integer> roleIds = adminParam.getRoleIds();
        if(CollUtil.isNotEmpty(roleIds)){
            adminRoleDao.deleteByAdminId(admin.getId());
            List<AdminRole> adminRoles = roleIds.stream().map(roleId -> new AdminRole(null, admin.getId(), roleId)).collect(Collectors.toList());
            adminRoleDao.insertList(adminRoles);
        }
        return ResultGenerator.genSuccessResult();

    }

    @Override
    public Result select(Integer id) {
        Admin admin = adminDao.selectByPrimaryKey(id);
        if(ObjectUtil.isNull(admin)){
            return ResultGenerator.genFailResult("管理员不存在");
        }
        AdminResult adminResult = BeanUtil.copyProperties(admin, AdminResult.class);
        return ResultGenerator.genSuccessResult(adminResult);
    }

    @Override
    public Result selectList(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<AdminResult> adminResults = adminDao.selectAll();
        PageInfo pageInfo = new PageInfo(adminResults);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Result uploadAvatar(MultipartFile avatar, Integer id) throws IOException {
        if (avatar.isEmpty()) {
            ResultGenerator.genFailResult("图片为空");
        }
        String fileName = avatar.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = uploadPath; //上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

            avatar.transferTo(dest);

        String filename = "/upload/" + fileName;
        Admin admin = new Admin();
        admin.setId(id);
        admin.setAvatar(filename);
        adminDao.updateByPrimaryKeySelective(admin);
        return ResultGenerator.genSuccessResult(filename);
    }
}
